package com.ruoyi.common.utils.tencentUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.bean.GroupInfo;
import com.tencentyun.Base64URL;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.Deflater;


/**
 * @description: 腾讯im基础配置
 * @author: zyb
 * @date: 2021/5/27 17:32
 */
@Slf4j
@Component
public class TencentCloudImUtil {
    private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
    private static final String APP_MANAGER = "administrator";
    private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";

    @Value("${IMConfig.sdkAppId}")
    private long sdkAppId;
    @Value("${IMConfig.secretKey}")
    private String secretKey;

    @Autowired
    private RedisServiceUtil redisServiceUtil;

    /**
     * 获取腾讯云用户签名
     */
    public String getTxCloudUserSig() {
        String userSig = redisServiceUtil.get(REDIS_IM_USER_SIG + APP_MANAGER);
        if (StringUtils.isEmpty(userSig)) {
            TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, secretKey);
            userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
            redisServiceUtil.set(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
        }
        return userSig;
    }

    /**
     * 获取腾讯im请求路径
     */
    private String getHttpsUrl(String imServiceApi, Integer random) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json", HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
    }

    /**
     * 导入单个账号
     *
     * @param userId 用户id
     */
    public void accountImport(String userId) {
        accountImport(userId, null);
    }

    /**
     * 获取 用户的UserSig
     *
     * @param userid
     * @param expire
     * @return
     */
    public String genUserSig(String userid, long expire) {
        return genUserSig(userid, expire, null);
    }

    private String genUserSig(String userid, long expire, byte[] userbuf) {
        long currTime = System.currentTimeMillis() / 1000;
        JSONObject sigDoc = new JSONObject();
        sigDoc.put("TLS.ver", "2.0");
        sigDoc.put("TLS.identifier", userid);
        sigDoc.put("TLS.sdkappid", sdkAppId);
        sigDoc.put("TLS.expire", expire);
        sigDoc.put("TLS.time", currTime);

        String base64UserBuf = null;
        if (null != userbuf) {
            base64UserBuf = Base64.getEncoder().encodeToString(userbuf).replaceAll("\\s*", "");
            sigDoc.put("TLS.userbuf", base64UserBuf);
        }
        String sig = hmacsha256(userid, currTime, expire, base64UserBuf);
        if (sig.length() == 0) {
            return "";
        }
        sigDoc.put("TLS.sig", sig);
        Deflater compressor = new Deflater();
        compressor.setInput(sigDoc.toString().getBytes(StandardCharsets.UTF_8));
        compressor.finish();
        byte[] compressedBytes = new byte[2048];
        int compressedBytesLength = compressor.deflate(compressedBytes);
        compressor.end();
        return (new String(Base64URL.base64EncodeUrl(Arrays.copyOfRange(compressedBytes, 0, compressedBytesLength)))).replaceAll("\\s*", "");
    }

    private String hmacsha256(String identifier, long currTime, long expire, String base64Userbuf) {
        String contentToBeSigned = "TLS.identifier:" + identifier + "\n" + "TLS.sdkappid:" + sdkAppId + "\n" + "TLS.time:" + currTime + "\n" + "TLS.expire:" + expire + "\n";
        if (null != base64Userbuf) {
            contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n";
        }
        try {
            byte[] byteKey = secretKey.getBytes(StandardCharsets.UTF_8);
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256");
            hmac.init(keySpec);
            byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes(StandardCharsets.UTF_8));
            return (Base64.getEncoder().encodeToString(byteSig)).replaceAll("\\s*", "");
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            return "";
        }
    }

    public void accountImport(String userId, String userName) {
        accountImport(userId, userName, null);
    }

    public void accountImport(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_IMPORT, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Identifier", userId);
        if (StringUtils.isNotEmpty(userName)) {
            jsonObject.put("Nick", userName);
        }
        if (StringUtils.isNotEmpty(faceUrl)) {
            jsonObject.put("FaceUrl", faceUrl);
        }
        log.info("腾讯云im导入单个账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账号，返回结果：{}", result);
    }

    /**
     * 导入多个账号
     *
     * @param userIds 用户id集合
     */
    public void multiAccountImport(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.MULTI_ACCOUNT_IMPORT, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Accounts", userIds);
        log.info("腾讯云im导入多个账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账户，返回结果：{}", result);
    }

    /**
     * 删除账号
     *
     * @param userIds 用户id集合
     */
    public void accountDelete(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_DELETE, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
        log.info("腾讯云im删除账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im删除账户，返回结果：{}", result);
    }

    /**
     * 查询账号是否已经导入im
     *
     * @param userIds 用户id集合
     */
    public String accountCheck(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_CHECK, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CheckItem", getUserIdJsonList(userIds));
        log.info("腾讯云im查询账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im查询账号，返回结果：{}", result);
        return result;
    }

    /**
     * 失效帐号登录状态
     *
     * @param userIds 用户id集合
     */
    public String accountKick(String userId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_KICK, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UserID", userId);
        log.info("腾讯云im失效帐号登录状态，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im失效帐号登录状态，返回结果：{}", result);
        return result;
    }

    private List<JSONObject> getUserIdJsonList(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("UserID", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }

    /**
     * 单发单聊消息
     *
     * @param syncOtherMachine 是否同步消息到发送方（1-同步，2-不同步）
     * @param fromUserId       发送方用户id
     * @param toUserId         接收方用户id
     * @param msgType          消息对象类型
     * @param msgContent       消息内容
     */
    public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", syncOtherMachine);
        if (StringUtils.isNotEmpty(fromUserId)) {
            // 发送方不为空表示指定发送用户，为空表示为管理员发送消息
            jsonObject.put("From_Account", fromUserId);
        }
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MsgRandom", random);
        List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
        jsonObject.put("MsgBody", msgBody);
        log.info("腾讯云im单发单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im单发单聊消息，返回结果：{}", result);
        return result;
    }

    /**
     * 批量发单聊消息
     *
     * @param syncOtherMachine 是否同步消息到发送方（1-同步，2-不同步）
     * @param fromUserId       发送方用户id
     * @param toUserIds        接收方用户id集合
     * @param msgType          消息对象类型
     * @param msgContent       消息内容
     */
    public String batchSendMsg(Integer syncOtherMachine, String fromUserId, List<String> toUserIds, String msgType, String msgContent) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.BATCH_SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", syncOtherMachine);
        if (StringUtils.isNotEmpty(fromUserId)) {
            // 发送方不为空表示指定发送用户，为空表示为管理员发送消息
            jsonObject.put("From_Account", fromUserId);
        }
        jsonObject.put("To_Account", toUserIds);
        jsonObject.put("MsgRandom", random);
        List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
        jsonObject.put("MsgBody", msgBody);
        log.info("腾讯云im批量发单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im批量发单聊消息，返回结果：{}", result);
        return result;
    }


    /**
     * 拼接发送消息内容
     *
     * @param msgType    消息类型
     * @param msgContent 发送消息内容
     * @return 消息内容
     */
    private List<JSONObject> getMsgBody(String msgType, String msgContent) {
        List<JSONObject> msgBody = new ArrayList<>();
        if (msgType.equals(TencentCloudImConstant.TIM_TEXT_ELEM)) {
            // 文本类型
            JSONObject msgBodyJson = new JSONObject();
            msgBodyJson.put("MsgType", msgType);
            JSONObject msgContentObj = new JSONObject();
            msgContentObj.put("Text", msgContent);
            msgBodyJson.put("MsgContent", msgContentObj);
            msgBody.add(msgBodyJson);
        }
        return msgBody;
    }

    /**
     * 查询单聊消息
     *
     * @param fromUserId 发送方用户id
     * @param toUserId   接收方用户id
     * @param maxCnt     查询条数
     * @param startTime  起始时间（单位：秒）
     * @param endTime    结束时间（单位：秒）
     * @param lastMsgKey 最后一条消息的 MsgKey
     * @return 单聊消息列表
     */
    public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_GET_ROAM_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", fromUserId);
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MaxCnt", maxCnt);
        jsonObject.put("MinTime", startTime);
        jsonObject.put("MaxTime", endTime);
        if (StringUtils.isNotEmpty(lastMsgKey)) {
            jsonObject.put("LastMsgKey", lastMsgKey);
        }
        log.info("腾讯云im查询单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im查询单聊消息，返回结果：{}", result);
        return result;
    }

    /**
     * 撤回单聊消息
     *
     * @param fromUserId 发送方用户id
     * @param toUserId   接收方用户id
     * @param msgKey     MsgKey
     */
    public void adminMsgWithDraw(String fromUserId, String toUserId, String msgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_MSG_WITH_DRAW, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", fromUserId);
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MsgKey", msgKey);
        log.info("腾讯云im撤回单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im撤回单聊消息，返回结果：{}", result);
    }

    /**
     * 设置单聊消息已读
     *
     * @param reportUserId 读取消息的用户
     * @param peerUserId   发送消息的用户
     */
    public void adminSetMsgRead(String reportUserId, String peerUserId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_SET_MSG_READ, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Report_Account", reportUserId);
        jsonObject.put("Peer_Account", peerUserId);
        log.info("腾讯云im设置单聊消息已读，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置单聊消息已读，返回结果：{}", result);
    }

    /**
     * 群组的详细信息
     *
     * @param groupIds
     */
    public List<GroupInfo> getGroupInfo(List<String> groupIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GET_GROUP_INFO, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupIdList", groupIds);
        log.info("腾讯云im取群组的详细信息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            JSONArray arrayList = res.getJSONArray("GroupInfo");
            List<GroupInfo> list = JSONArray.parseArray(arrayList.toJSONString(), GroupInfo.class);
            return list;
        }
        log.info("腾讯云im取群组的详细信息，返回结果：{}", result);
        return null;
    }

    /**
     * 获取 App 中的所有群组
     *
     * @param Limit
     * @param Next
     * @param GroupType
     */
    public void getAppidGroupList(Integer Limit, Integer Next, String GroupType) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GROUP_LIST, random);
        JSONObject jsonObject = new JSONObject();
        if (Limit != null) {
            jsonObject.put("Limit", Limit);
        }
        if (Next != null) {
            jsonObject.put("Next", Next);

        }
        if (StringUtils.isNotBlank(GroupType)) {
            jsonObject.put("GroupType", GroupType);
        }
        log.info("腾讯云im获取APP所有群组，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            JSONArray arrayList = res.getJSONArray("GroupIdList");
            List<String> groupIds = Lists.newArrayList();
            arrayList.stream().filter(Objects::nonNull).forEach(item -> {
                groupIds.add(((JSONObject) item).getString("GroupId"));
            });
            getGroupInfo(groupIds);
        }
        log.info("腾讯云im获取APP所有群组，返回结果：{}", result);
    }

    /**
     * 解散群
     *
     * @param groupId
     */
    public void destroyGroup(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.DESTROY_GROUP, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        log.info("腾讯云im解散群，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im解散群，返回结果：{}", result);
    }

    public void clearGroupAttr(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.CLEAR_GROUP_ATTR, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        log.info("腾讯云im清空群自定义属性，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im清空群自定义属性，返回结果：{}", result);
    }

    public String getGroupMsgPage(String groupId, Integer ReqMsgSeq, Integer ReqMsgNumber) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GROUP_MSG_GET_SIMPLE, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        if (ReqMsgSeq != null) {
            jsonObject.put("ReqMsgSeq", ReqMsgSeq);
        }
        if (ReqMsgNumber != null) {
            jsonObject.put("ReqMsgNumber", ReqMsgNumber);
        }
        log.info("腾讯云im拉取群历史消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im拉取群历史消息，返回结果：{}", result);
        return result;
    }

    /**
     * 增加群成员
     *
     * @param users
     * @param groupId
     * @return
     */
    public String groupsAddUsers(List<Map<String, Object>> users, String groupId, String huanyingyutext) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.ADD_GROUP_MEMBER, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        jsonObject.put("MemberList", users);
        log.info("腾讯云im增加群成员，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0 && StringUtils.isNotBlank(huanyingyutext)) {
            log.info("欢迎语_______>>>>:");
            //            sendGroupMsg(huanyingyutext, groupId);
            sendGroupMsgPt(huanyingyutext, groupId);
        }
        log.info("腾讯云im增加群成员，返回结果：{}", result);
        return result;
    }


    /**
     * 在群组中发送系统通知
     *
     * @param content
     * @param groupId
     * @return
     */
    public String sendGroupMsg(String content, String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.SEND_GROUP_SYSTEM_NOTIFICATION, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        jsonObject.put("Content", content);
        log.info("腾讯云im在群组中发送系统通知，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im在群组中发送系统通知，返回结果：{}", result);
        return result;
    }

    /**
     * 在群组中发送普通消息
     *
     * @param content
     * @param groupId
     * @return
     */
    public String sendGroupMsgPt(String content, String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.SEND_GROUP_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        jsonObject.put("MsgRandom", random);
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map = new HashMap<>();
        map.put("MsgType", "TIMTextElem");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("Text", content);

        map.put("MsgContent", map2);       // From_Account 对 To_Account 的好友备注，详情可参见
        list.add(map);
        jsonObject.put("MsgBody", list);

        log.info("腾讯云im在群组中发送普通消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im在群组中发送普通消息，返回结果：{}", result);
        return result;
    }

    public Map<String, Object> groupList(List<Map<String, Object>> list) {
        int listSize = list.size();
        int toIndex = 100;
        Map map = new HashMap();     //用map存起来新的分组后数据
        int keyToken = 0;
        for (int i = 0; i < list.size(); i += 100) {
            if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                toIndex = listSize - i;
            }
            List newList = new ArrayList<>(list.subList(i, i + toIndex));
            map.put("keyName" + keyToken, newList);
            keyToken++;
        }

        return map;
    }

    /**
     * 执行加好友
     *
     * @return
     */
    public String FRIEND_ADD(String account, String toAccount) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.RelationManage.FRIEND_ADD, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", account); // 需要为该 UserID 添加好友
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map = new HashMap<>();
        map.put("To_Account", toAccount);      // 好友的 UserID
        map.put("AddSource", "AddSource_Type_Sys");       // From_Account 对 To_Account 的好友备注，详情可参见
        map.put("Remark", "");          // From_Account 对 To_Account 的分组信息
        map.put("GroupName", "平台客服");
        map.put("AddWording", "");      //From_Account 和 To_Account 形成好友关系时的附言信息
        list.add(map);
        jsonObject.put("AddFriendItem", list);

        log.info("腾讯云im加好友，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im加好友，返回结果：{}", result);
        return result;
    }

    /**
     * 单发单聊消息
     *
     * @return
     */
    public String sendmsg(String account, String toAccount, String msgText) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", 1); // 消息不同步至发送方

        jsonObject.put("From_Account", account); //  消息发送方 UserID
        jsonObject.put("To_Account", toAccount);  //  消息接收方 UserID

        // jsonObject.put("MsgSeq", 93847636);
        jsonObject.put("MsgRandom", random);

        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map = new HashMap<>();
        map.put("MsgType", "TIMTextElem");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("Text", msgText);

        map.put("MsgContent", map2);       // From_Account 对 To_Account 的好友备注，详情可参见
        list.add(map);
        jsonObject.put("MsgBody", list);

        log.info("腾讯云im打招呼信息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im打招呼信息，返回结果：{}", result);
        return result;
    }


    /**
     * 获取用户在线状态
     *
     * @return
     */
    public String queryOnlineStatus(List Accounts) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.query_online_status, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("To_Account", Accounts);
        jsonObject.put("IsNeedDetail", 1);
        log.info("腾讯云im增加群成员，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im增加群成员，返回结果：{}", result);
        return result;
    }

    /**
     * 撤回单聊消息
     *
     * @param
     * @return
     */
    public String adminMsgwithdraw(String From_Account, String To_Account, String MsgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_MSG_WITH_DRAW, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", From_Account);
        jsonObject.put("To_Account", To_Account);
        jsonObject.put("MsgKey", MsgKey);
        log.info("腾讯云im撤回单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im撤回单聊消息，返回结果：{}", result);
        return result;
    }

    public Boolean addAdminGroupMember(String groupId, String members) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.ADD_GROUP_MEMBER, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        List<Map<String, Object>> list = Lists.newArrayList();
        JSONArray memberArr = JSONArray.parseArray(members);
        for (int i = 0; i < memberArr.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("Member_Account", memberArr.getString(i));
            list.add(map);
        }
        jsonObject.put("MemberList", list);
        log.info("腾讯云im增加群成员，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im增加群成员，返回结果：{}", result);
        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return true;
        }
        return false;
    }

    /**
     * 群主增加或删除管理员
     *
     * @param groupId
     * @param userId
     * @param type
     * @return
     */
    public Boolean managementGroupAdministrator(String groupId, String userId, String type) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.MODIFY_GROUP_MEMBER_INFO, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        jsonObject.put("Member_Account", userId);
        if (type.equals("add")) {
            jsonObject.put("Role", "Admin");
        }
        if (type.equals("del")) {
            jsonObject.put("Role", "Member");
        }
        log.info("腾讯云im群主增加或删除管理员，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im群主增加或删除管理员，返回结果：{}", result);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return true;
        }
        return false;
    }

    /**
     * 批量禁言和取消禁言
     *
     * @param groupId
     * @param type
     * @return
     */
    public Boolean managementGroupForbidSenMsg(String groupId, String members, String type) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.FORBID_SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);

        JSONArray memberArr = JSONArray.parseArray(members);
        jsonObject.put("Members_Account", memberArr);
        if (type.equals("add")) {
            jsonObject.put("MuteTime", 429496729);
        }
        if (type.equals("del")) {
            jsonObject.put("MuteTime", 0);
        }

        log.info("腾讯云im批量禁言和取消禁言，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im批量禁言和取消禁言，返回结果：{}", result);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return true;
        }
        return false;
    }


    /**
     * 获取被禁言群成员列表
     *
     * @param groupId
     * @return
     */
    public JSONArray getGroupMutedAccount(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GET_GROUP_SHUT_UIN, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);

        log.info("腾讯云im获取被禁言群成员列表，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im获取被禁言群成员列表，返回结果：{}", result);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return res.getJSONArray("MutedAccountList");
        }
        return null;
    }

    /**
     * 撤回群消息
     *
     * @param groupId
     * @return
     */
    public Boolean groupMsgRecall(String groupId, Long msgSeq) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GROUP_MSG_RECALL, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);

        List<Map<String, Object>> list = Lists.newArrayList();

        Map<String, Object> map = new HashMap<>();
        map.put("MsgSeq", msgSeq);
        list.add(map);

        jsonObject.put("MsgSeqList", list);

        log.info("腾讯云im,撤回群消息，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im,撤回群消息，返回结果：{}", result);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return true;
        }
        return false;
    }

    /**
     * 更新头像
     *
     * @param UserID
     * @param headUrl
     */
    public void updataHeadUrl(String UserID, String headUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.PortraitManage.PORTRAIT_SET, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", UserID);
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map = new HashMap<>();
        map.put("Tag", "Tag_Profile_IM_Image");
        map.put("Value", headUrl);
        list.add(map);
        jsonObject.put("ProfileItem", list);
        log.info("腾讯云im设置资料，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置资料，返回结果：{}", result);
    }

    /**
     * 更新个人信息
     *
     * @param UserID
     * @param headImgUrl
     * @param nickName
     * @param sex
     * @param sign
     */
    public void updataUserInfo(String UserID, String headImgUrl, String nickName, Integer sex, String sign) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.PortraitManage.PORTRAIT_SET, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", UserID);
        List<Map<String, Object>> list = Lists.newArrayList();

        if (StringUtils.isNotBlank(headImgUrl)) {
            Map<String, Object> map = new HashMap<>();
            map.put("Tag", "Tag_Profile_IM_Image");
            map.put("Value", headImgUrl);
            list.add(map);
        }
        if (StringUtils.isNotBlank(nickName)) {
            Map<String, Object> map = new HashMap<>();
            map.put("Tag", "Tag_Profile_IM_Nick");
            map.put("Value", nickName);
            list.add(map);
        }
        if (sex != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("Tag", "Tag_Profile_IM_Gender");
            map.put("Value", sex == 1 ? "Gender_Type_Male" : "Gender_Type_Female");
            list.add(map);
        }
        if (StringUtils.isNotBlank(sign)) {
            Map<String, Object> map = new HashMap<>();
            map.put("Tag", "Tag_Profile_IM_SelfSignature");
            map.put("Value", sign);
            list.add(map);
        }
        if (list.size() > 0) {
            jsonObject.put("ProfileItem", list);
            log.info("腾讯云im设置资料，请求参数：{}", jsonObject.toString());
            String result = HttpUtil.doPost2(httpsUrl, jsonObject);
            log.info("腾讯云im设置资料，返回结果：{}", result);
        }

    }

    public void main(String[] args) {
        String res = getGroupMsgPage("199", null, null);
        System.out.println(res);
    }

    public JSONArray getJoinedGroupList(String userId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.GET_JOINED_GROUP_LIST, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Member_Account", userId);

        log.info("腾讯云im,获取用户所加入的群组，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im,获取用户所加入的群组，返回结果：{}", result);

        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            JSONArray array = res.getJSONArray("GroupIdList");
            return array;
        }
        return null;
    }
}